<template>
  <div
    style="
      font-size: 14px;
      height: 40px;
      line-height: 40px;
      padding-left: 30px;
      border-radius: 4px;
      border-bottom: 4px solid #f6f8f9;
    "
  >
    <vab-icon icon="list-check" style="font-size: 16px" />
    艺人管理
    <B style="color: #a3a6ad"><vab-icon icon="arrow-right-s-line" /></B>
    艺人列表
  </div>
  <div class="comprehensive-table-container">
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form
          :inline="true"
          label-width="80px"
          :model="queryForm"
          @submit.prevent
        >
          <el-form-item label="综合检索">
            <el-input
              v-model="queryForm.key"
              clearable
              placeholder="输入关键词"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              style="
                background-color: #0d66b2;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="queryData"
            >
              查询
            </el-button>
            <el-button
              icon="el-icon-delete"
              style="
                background-color: #c9181e;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="handleDelete($event)"
            >
              删除
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
    </vab-query-form>
    <div style="margin-bottom: 10px">
      <el-button
        style="
          background-color: #18a55d;
          color: #fff;
          border: 0px;
          font-size: 14px;
        "
        @click="handleAdd"
      >
        <vab-icon icon="add-fill" style="font-size: 14px" />
        新增
      </el-button>
    </div>
    <el-table
      ref="tableSortRef"
      v-loading="listLoading"
      border
      :cell-style="{ padding: '4px 0 4px 0' }"
      :data="list"
      :header-cell-style="{
        background: '#E1EAF3 !important',
        'text-align': 'center',
      }"
      :height="500"
      :row-style="{ background: '#E4F2FF' }"
      stripe
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column
        align="center"
        :selectable="isSelectable"
        show-overflow-tooltip
        type="selection"
        width="55"
      />

      <el-table-column
        align="center"
        fixed="left"
        label="姓名"
        min-width="200px"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="所属专题"
        min-width="100px"
        prop="specialStr"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="头像"
        min-width="80px"
        prop="avatarUrl"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-image
            :preview-src-list="[row.avatarUrl]"
            :src="row.avatarUrl"
            style="height: 60px; width: 60px"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="标签"
        min-width="100px"
        prop="label"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="创建时间"
        min-width="120px"
        prop="createTime"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="更新时间"
        min-width="120px"
        prop="updateTime"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        show-overflow-tooltip
        width="120"
      >
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button
            style="color: #c9181e"
            type="text"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :page-sizes="[5, 10, 30, 40, 50, 100]"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <table-edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    computed,
    defineComponent,
    getCurrentInstance,
    onBeforeMount,
    onBeforeUnmount,
    onMounted,
    reactive,
    toRefs,
    watch,
  } from 'vue'
  import { useStore } from 'vuex'
  import { useRouter, useRoute } from 'vue-router'
  import {
    exportTemplate,
    doBlack,
    doInjury,
    getExcelStatus,
    delExcelExecute,
  } from '@/api/employee'
  import { getList, doDelete } from '@/api/artist'
  import TableEdit from './components/TableEdit'
  import { baseURL } from '@/config'

  export default defineComponent({
    name: 'ComprehensiveTable',
    components: {
      TableEdit,
    },
    setup() {
      const store = useStore()
      const router = useRouter()
      const route = useRoute()
      const { proxy } = getCurrentInstance()

      const state = reactive({
        editRef: null,
        editRefBlack: null,
        tableSortRef: null,
        fold: false,
        height: proxy.$baseTableHeight(2) - 30,
        imgShow: true,
        loading1: false,
        showUpload: true,
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        excelStatus: null,
        showEditService: false,
        service_tel: [],
        queryForm: {
          pageNo: 1,
          pageSize: 5,
          key: '',
          type: 'COMPANY_NATURE',
        },
        parentAreaCodes: {
          first: null,
          second: null,
        },
        dialogTableVisible: false,
        baseURL: null,
        headers: null,
        isUploadLoding: false,
        file: {
          resourceId: null,
          fileName: null,
        },
      })
      state.baseURL = baseURL
      state.headers = {
        Authorization: computed(() => store.getters['user/token']),
      }

      watch(
        () => route.path,
        (value) => {
          if (value === '/system/admin/comprehensiveTable') fetchData()
        }
      )

      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { records: list, total },
        } = await getList(state.queryForm)
        state.list = list
        state.total = total
        state.listLoading = false
      }
      const loadParent = () => {
        if (state.parentAreaCodes.second) {
          state.parentAreaCodes.second = null
          state.queryForm.parentAreaCode = state.parentAreaCodes.first.code
          fetchData()
        } else {
          state.parentAreaCodes.first = null
          state.queryForm.parentAreaCode = '100000'
          fetchData()
        }
      }

      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const handleAdd = () => {
        state['editRef'].showEdit(state.parentAreaCodes)
      }
      const handleEdit = (row) => {
        state['editRef'].showEdit(row)
      }

      const todoBlack = async (row, target) => {
        let obj = {
          employeeId: row.id,
          target: target,
          blackDesc: row.blackDesc,
          blackReason: row.blackReason,
        }
        if (target == 0) {
          proxy.$baseConfirm(
            '确定恢复正常吗？异常原因如下【' + row.blackDesc + '】',
            '恢复正常',
            async () => {
              const { msg, code } = await doBlack(obj)
              if (code != 200) {
                proxy.$baseMessage(msg, 'error')
                return
              }
              fetchData()
            }
          )
        } else {
          state['editRefBlack'].showEdit(obj)
        }
      }

      const todoInjury = async (row, target) => {
        let obj = {
          employeeId: row.id,
          target: target,
        }
        proxy.$baseConfirm(
          target == 0 ? '确定取消工伤状态吗？' : '确定处理为工伤状态吗',
          null,
          async () => {
            const { msg, code } = await doInjury(obj)
            if (code != 200) {
              proxy.$baseMessage(msg, 'error')
              return
            }
            fetchData()
          }
        )
      }

      const handleHeight = () => {
        if (state.fold) state.height = proxy.$baseTableHeight(2) - 47
        else state.height = proxy.$baseTableHeight(3) - 30
      }

      // const isSelectable = (row, index) => {
      const isSelectable = () => {
        // console.log(index)
        // return row.isWorking == 0
        return true
      }
      const tableSortChange = () => {
        const imageList = []
        state['tableSortRef'].tableData.forEach((item) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      }
      const setSelectRows = (val) => {
        state.selectRows = val
      }

      const handleDetail = (row) => {
        if (row.id)
          router.push({
            path: '/employee/detail',
            query: row,
          })
        else {
          proxy.$baseMessage(
            '请选择一行进行详情页跳转',
            'error',
            'vab-hey-message-error'
          )
        }
      }

      const handleDownloadTemplate = async () => {
        proxy.$baseConfirm(
          '导入时请使用该模板导入，请勿修改表头、工作簿名称，按示例添加数据，并删除示例部分',
          null,
          async () => {
            exportTemplate(state.queryForm)
          }
        )
      }

      const toClickUpLoad = () => {
        document.querySelector('.main_img_upload input').click()
      }

      const openDialog = async () => {
        const {
          data: { status },
        } = await getExcelStatus()
        state.excelStatus = status
        state.dialogTableVisible = true
      }

      const handleSuccess = (res, file) => {
        if (res.stat == 200) {
          state.file.resourceId = res.resourceId
          state.file.fileName = file.name
          handleChange()
        } else {
          proxy.$baseMessage(res.msg, 'error', 'vab-hey-message-error')
        }
      }

      const jumpTemp = (step) => {
        let obj = state.file
        obj.step = step
        router.push({
          path: '/employee/temp',
          query: obj,
        })
      }

      const clearTask = async () => {
        await delExcelExecute()
        openDialog()
      }
      const handleChange = () => {
        let fileName = state.file.fileName
        if (fileName) {
          proxy.$baseConfirm('确定导入【' + fileName + '】吗？', null, () => {
            router.push({
              path: '/employee/temp',
              query: state.file,
            })
          })
        } else {
          proxy.$baseMessage(
            '文件有误，请重试',
            'warning',
            'vab-hey-message-success'
          )
        }
      }

      const handleDelete = (row) => {
        let arr = []
        if (row.id) {
          proxy.$baseConfirm('你确定要删除当前项吗', null, async () => {
            proxy.$baseConfirm(
              '即将删除选中数据，请再次确认',
              null,
              async () => {
                arr.push(row.id)
                const { msg } = await doDelete({ ids: arr })
                proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
                await fetchData()
              }
            )
          })
        } else {
          if (state.selectRows.length > 0) {
            state.selectRows.map((item) => arr.push(item.id))
            proxy.$baseConfirm('你确定要删除选中项吗', null, async () => {
              proxy.$baseConfirm(
                '即将删除选中数据，请再次确认',
                null,
                async () => {
                  const { msg } = await doDelete({ ids: arr })
                  proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
                  await fetchData()
                }
              )
            })
          } else {
            proxy.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })
      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })
      onMounted(() => {
        fetchData()
      })

      return {
        ...toRefs(state),
        handleSizeChange,
        handleCurrentChange,
        handleHeight,
        tableSortChange,
        setSelectRows,
        handleDetail,
        fetchData,
        queryData,
        handleAdd,
        handleEdit,
        handleDownloadTemplate,
        toClickUpLoad,
        handleSuccess,
        handleChange,
        todoBlack,
        todoInjury,
        openDialog,
        handleDelete,
        isSelectable,
        jumpTemp,
        clearTask,
        loadParent,
      }
    },
    methods: {},
  })
</script>
